package br.sed.theenemy.presentation.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.exception.InvalidUniqueBeanException;
import br.sed.theenemy.business.exception.InvalidUserException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyConstants;
import br.sed.theenemy.presentation.UserSession;
import br.sed.theenemy.presentation.form.ProfileForm;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 * 
 */
public class ProfileAction extends DispatchAction {

	// forwards
    private static final String PROFILE_PAGE = "ProfilePage";
    private static final String LOGIN_PAGE = "LoginPage";
    
	public ActionForward unspecified(final ActionMapping mapping,
	           final ActionForm form, final HttpServletRequest request, 
	           final HttpServletResponse response) {
		ProfileForm profileForm = (ProfileForm) form;
		Services services = Services.getInstance();
				
		final UserSession session = new UserSession(request, false);
        final User userLogged = session.getLoggedUser();
        
        if (userLogged == null) {
            // User not logged in, redirect to login.jsp
            return mapping.findForward(LOGIN_PAGE);
        }
        
        Long permalinkId = profileForm.getId();
        User user = null;
        if(permalinkId == null || permalinkId == 0){
        	user = userLogged;
        }else{
        	try {
				user = services.findUserById(permalinkId);
			} catch (InvalidUniqueBeanException e) {
			    return mapping.findForward(EnemyConstants.ERROR_404);
			} catch (DBException e) {
			    return mapping.findForward(EnemyConstants.ERROR_PAGE);
			} catch (InvalidUserException e) {
                // TODO 
            }
        }
        
        profileForm.setId(user.getId());
    	profileForm.setFirstName(user.getFirstName());
    	profileForm.setLastName(user.getLastName());
        profileForm.setProfileImg(user.getImgUrl());
    			
        // User logged redirect to profile
        return mapping.findForward(PROFILE_PAGE);
        
	}
}
